package com.sihai.ehr.service.impl;

import java.text.MessageFormat;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

import com.sihai.core.DataAccessor;
import com.sihai.core.DynamicQuery;
import com.sihai.core.Limit;
import com.sihai.core.LimitedList;
import com.sihai.core.QueryCreator;
import com.sihai.core.Sorter;
import com.sihai.ehr.model.biz.SalarySocialInsurance;
import com.sihai.ehr.model.biz.SalaryStructure;
import com.sihai.ehr.model.biz.SalaryStructureDetail;
import com.sihai.ehr.model.sys.SalaryFrameworkEnum;
import com.sihai.ehr.service.SalaryInsuranceService;
import com.sihai.ehr.service.SalaryStructService;
import org.springframework.util.Assert;

/**
 * 社保管理服务实现
 * 
 * @author henry
 * 
 */
@Service("salaryStructService")
public class SalaryStructServiceImpl implements SalaryStructService {

	@Resource
	private DataAccessor dataAccessor;

	@Override
	public SalaryStructure get(Long id) {
		if (id == null || id < 0) {
			throw new RuntimeException("【传入参数非法】");
		}
		try {
			return dataAccessor.get(SalaryStructure.class, id);
		} catch (Exception e) {
			throw new RuntimeException("【异常原因：获取定性考核员工分数明细数据库发生异常】【异常说明：+" + e.getMessage() + "】【发生地点：SalaryInsuranceServiceImpl.get;参数id=" + id + " 】");
		}
	}

	@Override
	public void save(SalaryStructure structure) {
		if (structure == null || structure.getOrganization() == null) {
			throw new RuntimeException("【insurance对象参数异常】");
		}
		try {
			dataAccessor.saveOrUpdate(structure);
		} catch (Exception e) {
			throw new RuntimeException("【异常原因：保存薪资架构对象到数据库发生异常】【异常说明：" + e.getMessage() + "】【发生地点：SalaryStructServiceImpl.save】");
		}
	}

	@Override
	public SalaryStructureDetail getStructureDetailByIdAndLnkType(final Long id, final SalaryFrameworkEnum frameworkEnum) {
		if (id == null || frameworkEnum == null) {
			throw new RuntimeException("【id或frameworkEnum对象参数异常】");
		}
		try {
			List<SalaryStructureDetail> listDetails = dataAccessor.findByQuery(SalaryStructureDetail.class, new QueryCreator() {

				@Override
				public Query createQuery(Session session) {
					DynamicQuery dynamicQuery = new DynamicQuery("from SalaryStructureDetail s where 1 <> 2");
					dynamicQuery.appendIfNotNull("and s.salaryStructure.id =:id", "id", id);
					dynamicQuery.appendIfNotNull("and s.linkedDataType =:linkedDataType", "linkedDataType", frameworkEnum);

					return dynamicQuery.build(session);
				}
			}, null, null);
			if (listDetails != null && listDetails.size() > 0) {
				return listDetails.get(0);
			} else {
				return null;
			}
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public void deleteStructures(final String ids) {
		if (ids == null || ids.isEmpty()) {
			throw new RuntimeException("【参数异常：ids为空】");
		}
		try {
			// 第一步删除细节
			dataAccessor.batchUpdate(new QueryCreator() {
				@Override
				public Query createQuery(Session session) {
					return session.createQuery(MessageFormat.format("delete from SalaryStructureDetail s where s.salaryStructure.id in ({0})", ids));
				}
			});
			dataAccessor.batchUpdate(new QueryCreator() {
				@Override
				public Query createQuery(Session session) {
					return session.createQuery(MessageFormat.format("update SalaryStructure s set s.cancel=1 where s.id in ({0})", ids));
				}
			});
		} catch (Exception e) {
			throw new RuntimeException("【异常原因：移出社保信息数据库发生异常】【异常说明：" + e.getMessage() + "】【发生地点：SalaryStructServiceImpl.deleteStructures】");
		}
	}

	@Override
	public void deleteStructureDetails(final Long structId) {
		if (structId == null && structId <= 0) {
			throw new RuntimeException("【参数异常：insuranceId参数错误】");
		}
		try {
			dataAccessor.batchUpdate(new QueryCreator() {
				@Override
				public Query createQuery(Session session) {
					return session.createQuery(MessageFormat.format("delete from SalaryStructureDetail d where d.salaryStructure.id={0}", structId));
				}
			});
		} catch (Exception e) {
			throw new RuntimeException("【异常原因：移出社保项目细节信息数据库发生异常】【异常说明：" + e.getMessage() + "】【发生地点：SalaryStructServiceImpl.deleteStructureDetails】");
		}
	}

	@Override
	public LimitedList<SalaryStructure> find(final Long organizationId, Limit limit, Sorter sorter) {
		if (organizationId == null || organizationId < 0) {
			throw new RuntimeException("【传入参数非法】");
		}
		try {
			return dataAccessor.findByQuery(SalaryStructure.class, new QueryCreator() {

				@Override
				public Query createQuery(Session session) {
					DynamicQuery dynamicQuery = new DynamicQuery("from SalaryStructure s where 1 <> 2");
					dynamicQuery.appendIfNotNull("and s.organization.id =:organizationId", "organizationId", organizationId);
					dynamicQuery.append("and s.cancel=0");
					return dynamicQuery.build(session);
				}
			}, limit, sorter);
		} catch (Exception e) {
			throw new RuntimeException("【异常原因：获取考核周期列表时数据库发生异常】【异常说明：+" + e.getMessage() + "】【发生地点：SalaryStructServiceImpl.find;参数organizationId=" + organizationId + "】");
		}
	}

	@Override
	public LimitedList<Object[]> findForGrade(Long organizationId, Limit limit, Sorter sorter) throws Exception {
		Assert.notNull(organizationId, "organization id mustn't null");
		return dataAccessor.findByHql(Object[].class, "select ss.id, ss.projectTitle from SalaryStructure ss where ss.cancel=0 and ss.organization.id = ?", new Object[] { organizationId }, limit,
				sorter);
	}

}
